<template>
  <div>
    <div class="search-bar">
      <el-input
          class="custom-input"
          placeholder="请输入问题"
          v-model="searchKey"
          clearable>
      </el-input>
      <h3>总问题：{{allQuestion.length}}</h3>
    </div>
    <div class="table-container">
      <table class="student-table">
        <thead>
        <tr class="sticky-header">
          <th>id</th>
          <th>昵称</th>
          <th>头像</th>
          <th>问题</th>
          <th>时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="q in filquestion" :key="q.id">
          <td>{{ q.id}}</td>
          <td>{{ q.nickname }}</td>
          <td>
            <img class="headimgurl" :src="q.headimgUrl" alt="Avatar" />
          </td>
          <td style="width: 100px; overflow: hidden">{{ q.question }}</td>
          <td>{{q.time}}</td>
          <td><el-button
              type="danger"
              icon="el-icon-delete"
              circle
              class="delete-button"
              @click="deleteQuestion(q.id)"></el-button></td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "AllQuestions",
  data(){
    return {
      allQuestion:[],
      searchKey:''
    }
  },
  mounted() {
  axios.post('/api/question')
      .then(res =>{
        this.allQuestion = res.data.msg
      })
      .catch(err =>{
        alert(err)
      })
   },
  computed:{
    filquestion(){
      return this.allQuestion.filter((item) =>{
        return item.question.indexOf(this.searchKey) !== -1
      })
    }
  },
  methods:{
    deleteQuestion(id){
      if (confirm('确认删除此问题吗？')){
        axios.post(`/delect/api/question/${id}`)
            .then(res =>{
              if (res.data.code === 0){
                alert('问题删除成功！')
                this.$router.go(0)
              } else {
                alert('问题删除失败！')
              }
            })
            .catch(err =>{
              alert(err)
            })
      }
    }
  }
}
</script>

<style scoped>
.custom-input {
  width: 100%; /* 输入框宽度自适应父容器宽度 */
  max-width: 500px; /* 设置输入框的最大宽度为 500 像素 */
}
.search-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  text-align: center;
}

.table-container {
  height: 550px; /* 设置表格容器的高度，根据实际情况调整 */
  overflow-y: scroll;
}
.sticky-header {
  position: sticky;
  top: 0;
  background-color: white;
}
.student-table {
  width: 100%;
  border-collapse: collapse;
}
.student-table tr:hover .delete-button {
  visibility: visible;
}
.delete-button {
  visibility: hidden;
}

.student-table th,
.student-table td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.student-table th {
  background-color: #f5f5f5;
}
.headimgurl{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>